//
//  AsyncGetConnection.m
//  AsyncGetConnection
//
//  Created by ZhiPeng.Y on 15/9/9.
//  Copyright (c) 2015年 ZP.Y. All rights reserved.
//

#import "AsyncGetConnection.h"
#import "Reachability.h"
#import "SaveTools.h"

@interface AsyncGetConnection ()<NSURLConnectionDelegate, NSURLConnectionDataDelegate>

@property (nonatomic, copy) NSString *file;
@end

@implementation AsyncGetConnection

- (void)dealloc {
    [_receiveData release];
    Block_release(_dataBlock);
    [super dealloc];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

+ (BOOL)judgeConnection {
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) { // 没网
        return NO;
    } else if (status == ReachableViaWWAN) { // 3G
        return YES;
    } else if (status == ReachableViaWiFi) { // wifi
        return YES;
    }
    return NO;
}


//1.开始网络请求
- (void)startConnectionWithURL:(NSString *)url {
    NSURL *urlStr = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urlStr];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

//2.执行协议方法(接收URL请求响应,初始化用来装数据的容器receiveData)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    self.receiveData = [NSMutableData data];
}

//3.执行协议方法(接收加载数据,把数据加载到receiveData中)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.receiveData appendData:data];
}

//4.执行协议方法(连接加载完成,把获得的数据返回给视图控制器)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //缓存
    [SaveTools saveDataWith:self.file directory:NSLibraryDirectory data:self.receiveData];
    self.dataBlock(self.receiveData);
}

//5.网络错误
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@" NetWorking Connection Error");
}

//6.封装类方法(网络请求)
+ (instancetype)asyncGetConnectionWithURL:(NSString *)url parameters:(NSDictionary *)parameters block:(void(^)(NSData *data))block {
    NSString *temp = @"";
    for (NSString *key in parameters) {
        if (temp.length == 0) {
            temp = [NSString stringWithFormat:@"%@=%@", key, [parameters objectForKey:key]];
        } else {
            temp = [NSString stringWithFormat:@"%@&%@=%@", temp, key, [parameters objectForKey:key]];
        }
    }
    NSString *newURL = [NSString stringWithFormat:@"%@%@", url, temp];
    newURL = [newURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"%@", newURL);
    NSString *file = [NSString stringWithFormat:@"%@", newURL];
    file = [file stringByReplacingOccurrencesOfString:@"/" withString:@""];
    file = [file stringByReplacingOccurrencesOfString:@":" withString:@""];
    
    
    //判断当前网络状态,没有网络的情况下,读取缓存
    BOOL judge = [AsyncGetConnection judgeConnection];
    if (judge) {
        AsyncGetConnection *asyncGet = [[AsyncGetConnection alloc] init];
        asyncGet.dataBlock = block;
        asyncGet.file = file;
        [asyncGet startConnectionWithURL:newURL];
        return [asyncGet autorelease];
    } else {
        NSData *data = [SaveTools readDataWithName:file directory:NSLibraryDirectory];
        //保护,一旦为空 ,就不返回data
        if (data != nil) {
            block(data);
        }
    }
    return nil;
}

+(instancetype)asyncPOSTConnectionWithURL:(NSString *)url parameters:(NSDictionary *)parameters block:(void (^)(NSData *data))block
{
    NSString *temp = @"";
    for (NSString *key in parameters) {
        if (temp.length == 0) {
            temp = [NSString stringWithFormat:@"?%@=%@",key,[parameters objectForKey:key]];
        }else
        {
            temp = [NSString stringWithFormat:@"%@&%@=%@",temp,key,[parameters objectForKey:key]];
        }
    }
    NSString *newUrl = [NSString stringWithFormat:@"%@%@",url,temp];
//    newUrl = [newUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSString *file = [NSString stringWithFormat:@"%@", newUrl];
//    file = [file stringByReplacingOccurrencesOfString:@"/" withString:@""];
//    file = [file stringByReplacingOccurrencesOfString:@":" withString:@""];
//    
    //判断当前网络状态,没有网络的情况下,读取缓存
//    BOOL judge = [AsyncGetConnection judgeConnection];
//    if (judge) {
//        AsyncGetConnection *asyncGet = [[AsyncGetConnection alloc] init];
//        asyncGet.dataBlock = block;
//        asyncGet.file = file;
//        [asyncGet startAsyncPostConnection:newUrl];
//        return [asyncGet autorelease];
//    } else {
//        NSData *data = [SaveTools readDataWithName:file directory:NSLibraryDirectory];
//        //保护,一旦为空 ,就不返回data
//        if (data != nil) {
//            block(data);
//        }
//    }
//    return nil;
//    return nil;
//    url = [newUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        AsyncGetConnection *asyncPost = [[AsyncGetConnection alloc] init];
        asyncPost.dataBlock = block;
        [asyncPost startAsyncPostConnection:newUrl dic:parameters];
        return [asyncPost autorelease];


}

- (void)startAsyncPostConnection:(NSString *)urlStr dic:(NSDictionary *)dic
{
//    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *myurl = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:myurl]autorelease];
    [request setHTTPMethod:@"POST"];
    NSData *myData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    [request setHTTPBody:myData];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
//    return urlStr;
}

@end
